package jp.sourceforge.akjrcp.audiotools;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;

import jp.sourceforge.akjrcp.akj_betas.Akj_betasPlugin;
import jp.sourceforge.akjrcp.akj_betas.Messages;
import jp.sourceforge.akjrcp.audio.Scale;
import jp.sourceforge.akjrcp.commons.ui.FileDirChoicer;
import jp.sourceforge.akjrcp.commons.ui.AbstractFileDirChoicer.FileStatusChangeEvent;
import jp.sourceforge.akjrcp.commons.ui.AbstractFileDirChoicer.FileStatusChangeListener;
import jp.sourceforge.akjrcp.commons.ui.widget.WidgetBuilder;
import jp.sourceforge.akjrcp.commons.util.FileNameUtils;
import jp.sourceforge.akjrcp.ffmpeg.FFMpegCommandUtil;
import jp.sourceforge.akjrcp.ffmpeg.FFMpegUI;
import jp.sourceforge.akjrcp.ffmpeg.FFMpegUtils;
import jp.sourceforge.akjrcp.ffmpeg.SimpleCommandExecuter;
import jp.sourceforge.akjrcp.snack.ESPS;
import jp.sourceforge.akjrcp.snack.PitchExecuter;
import jp.sourceforge.akjrcp.snack.PitchToVocaloidMIDI;
import jp.sourceforge.akjrcp.subtitle.StandardSubObject;
import jp.sourceforge.akjrcp.subtitle.srt.SRTList;
import jp.sourceforge.akjrcp.subtitle.srt.SRTParser;
import jp.sourceforge.akjrcp.tools.OtherToolsSettingPage;
import jp.sourceforge.akjrcp.ui.param.ParamBoolean;
import jp.sourceforge.akjrcp.ui.param.ParamCombo;
import jp.sourceforge.akjrcp.ui.param.ParamItem;
import jp.sourceforge.akjrcp.ui.param.ParamItemActionListener;
import jp.sourceforge.akjrcp.ui.param.ParamScale;
import jp.sourceforge.akjrcp.ui.param.ParamSpinner;
import jp.sourceforge.akjrcp.ui.param.ParamSpinnerAndScale;
import jp.sourceforge.akjrcp.ui.param.ParamText;
import jp.sourceforge.akjrcp.ui.param.ParamTextArea;
import jp.sourceforge.akjrcp.util.ExecutingControler;
import jp.sourceforge.akjrcp.util.StatusBarUtils;
import jp.sourceforge.akjrcp.util.ExecutingControler.ExecutingControlButton;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.part.ViewPart;


public class WavToVocaloidMidiViewer extends ViewPart {
	public static Log log=LogFactory.getLog(WavToVocaloidMidiViewer.class);
	
	public static final String ID = WavToVocaloidMidiViewer.class.getName();
	
	private ParamCombo min_picth;
	private ParamCombo max_pitch;

	private FileDirChoicer tmpDirChooser;
	private FileDirChoicer inputWavFileChooser;
	private FileDirChoicer inputSrtFileChooser;
	
	private FileDirChoicer outputFileChooser;
	private WavToVocaloidMIDIExecute wavToMidiExecuter;
	
	private ParamSpinnerAndScale minVolumeScale;
	private ParamScale noteShiftScale;

	private Label statusLabel;

	private ParamBoolean forceInsertSubtile;

	private ParamBoolean ignoreOffsetBoolean;
	
	private ParamBoolean setPitchBoolean;
	private ParamBoolean setVelocityBoolean;

	private ParamScale strechTimeSale;



	private ParamSpinner defaultPitchSpinner;

	private ParamSpinner defaultVelocitySpinner;

	private ParamCombo bentSens;
	private ParamCombo preMeasure;
	private ParamScale genderScale;

	private ParamBoolean setPitchDetailBoolean;

	private ParamBoolean setVelocityDetailBoolean;

	private ParamCombo smoothLevel;
	
	private ParamBoolean vocaloid1;
	public class ExportFileSet implements FileStatusChangeListener{

		public void addList(FileStatusChangeEvent event) {
			String path=event.getFilePath();
			if(!path.equals("")){
				setInputWave(path);
			}else{
				updateStatus();
			}
			
		}

		public void removeList(FileStatusChangeEvent event) {
			// TODO Auto-generated method stub
			
		}

	
		
	}
	
	public void createPartControl(Composite parent) {
		
		wavToMidiExecuter = new WavToVocaloidMIDIExecute();
		
		parent.setLayout(new GridLayout(1,false));
		
		
		
FileSelected selectedListener=new FileSelected();
		
		tmpDirChooser = new FileDirChoicer(parent,SWT.BORDER,FileDirChoicer.DIR,Messages.getString("spumux.tmp_dir"));
		tmpDirChooser.setToolTipText(Messages.getString("spumux.tmp_dir_tooltips"));
		tmpDirChooser.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		tmpDirChooser.addFileListChangeListener(selectedListener);
		
		tmpDirChooser.setFilePath(Akj_betasPlugin.getDefault().getPreferenceStore().getString(OtherToolsSettingPage.PATH_ASCII_TEMPORARY));
		tmpDirChooser.addFileListChangeListener(new FileStatusChangeListener(){

			public void addList(FileStatusChangeEvent event) {
				Akj_betasPlugin.getDefault().getPreferenceStore().setValue(OtherToolsSettingPage.PATH_ASCII_TEMPORARY, tmpDirChooser.getAbsoluteFilePath());
			}

			public void removeList(FileStatusChangeEvent event) {
				Akj_betasPlugin.getDefault().getPreferenceStore().setValue(OtherToolsSettingPage.PATH_ASCII_TEMPORARY, tmpDirChooser.getAbsoluteFilePath());
				
			}});
		
		
		Composite s1=createSplitComposite(parent,2,false,new GridData(GridData.FILL_HORIZONTAL));
		
		Composite s1_2=createSplitComposite(s1,2,false,new GridData(GridData.FILL_HORIZONTAL));
		
		//combo
		max_pitch=new ParamCombo(s1_2,SWT.NULL,"max_pitch",Messages.getString("wav2midi.max_pitch"),new String[]{"400","500","600","700","800","1000","1200","1400"});
		max_pitch.setValue("600");
		max_pitch.setToolTipText(Messages.getString("wav2midi.max_pitch_tooltip"));
		//combo
		min_picth=new ParamCombo(s1_2,SWT.NULL,"ignore_end",Messages.getString("wav2midi.min_pitch"),new String[]{"0","40","60","80","100","150","200","300","400","500","600"});
		min_picth.setValue("60");	//for voice
		min_picth.setToolTipText(Messages.getString("wav2midi.min_pitch_tooltip"));
		
		Composite s1_3=createSplitComposite(s1,2,false,new GridData(GridData.FILL_HORIZONTAL));
		
		ignoreOffsetBoolean = new ParamBoolean(s1_3,SWT.NULL,"ignore_offset",Messages.getString("wav2midi.ignore_offset"));
		ignoreOffsetBoolean.setValue("1");
		
		forceInsertSubtile = new ParamBoolean(s1_3,SWT.NULL,"force_intsert",Messages.getString("wav2midi.force_intsert"));
		forceInsertSubtile.setValue("1");
		
		
		
	    noteShiftScale=new ParamScale(s1,SWT.NULL,"note_shift",Messages.getString("wav2midi.note_shift"));
	    noteShiftScale.setOffset(-24);
	    noteShiftScale.setMaximum(48);
	    noteShiftScale.setValue(0);
	    noteShiftScale.setToolTipText(Messages.getString("wav2midi.note_shift_tooltip"));
		minVolumeScale=new ParamSpinnerAndScale(s1,SWT.NULL,"min_volume",Messages.getString("wav2midi.min_volume"));
		minVolumeScale.setMinimum(1);
		minVolumeScale.setMaximum(9000);
		minVolumeScale.setValue(""+100);	//for catch no voice sounds
		minVolumeScale.getSpinnerAndScale().getSpinner().setPageIncrement(10);
		minVolumeScale.setToolTipText(Messages.getString("wav2midi.min_volume_tooltip"));
		
		
		Composite s2=createSplitComposite(parent,5,false,new GridData(GridData.FILL_HORIZONTAL));
		
		strechTimeSale = new ParamScale(s2,SWT.NULL,"strech_time",Messages.getString("wav2midi.strech_time")){
					protected String toValue(String n){
						double num=Integer.parseInt(n);
						String ret=""+(double)getScale().getSelection()/10;
						while(ret.length()<num){
							ret=" "+ret;	
							}
						return ret;
					}
				};
		strechTimeSale.setMinimum(3);
		strechTimeSale.setMaximum(30);
		strechTimeSale.setValue(10);
		
		
		

		String[] preMeasures=new String[4];
		for (int i = 0; i < preMeasures.length; i++) {
			preMeasures[i]=""+(i+1);
		}
		
		preMeasure=new ParamCombo(s2,SWT.NULL,"preMeasure",Messages.getString("wav2vsq.pre_measure"),preMeasures);
		String[] bendSenss=new String[24];
		for (int i = 0; i < bendSenss.length; i++) {
			bendSenss[i]=""+(i+1);
		}
		bentSens=new ParamCombo(s2,SWT.NULL,"bendSens",Messages.getString("wav2vsq.bend_sens"),bendSenss);
		bentSens.setValue("8");
		
		
		genderScale=new ParamScale(s2,SWT.NULL,"gender",Messages.getString("wav2vsq.gender"));
	   
		genderScale.setMaximum(127);
		genderScale.setValue(64);
		
		Composite s3=createSplitComposite(parent,6,false,new GridData(GridData.FILL_HORIZONTAL));
		
		setPitchBoolean = new ParamBoolean(s3,SWT.NULL,"ignore_offset",Messages.getString("wav2midi.set_pitch"));
		setPitchBoolean.setValue("1");
		
		setPitchDetailBoolean = new ParamBoolean(s3,SWT.NULL,"pitch_detail",Messages.getString("wav2midi.set_pitch_detail"));
		setPitchDetailBoolean.setValue("1");
		
		defaultPitchSpinner = new ParamSpinner(s3,SWT.NULL,"default_pitch",Messages.getString("wav2midi.default_pitch"));
		defaultPitchSpinner.setMinimum(21);
		defaultPitchSpinner.setMaximum(108);
		defaultPitchSpinner.setValue(""+48);//C3
		
		setVelocityBoolean = new ParamBoolean(s3,SWT.NULL,"ignore_offset",Messages.getString("wav2midi.set_velocity"));
		setVelocityBoolean.setValue("0");
		
		setVelocityDetailBoolean = new ParamBoolean(s3,SWT.NULL,"velocity_detail",Messages.getString("wav2midi.set_velocity_detail"));
		setVelocityDetailBoolean.setValue("0");
		
		defaultVelocitySpinner = new ParamSpinner(s3,SWT.NULL,"default_velocity",Messages.getString("wav2midi.default_velocity"));
		defaultVelocitySpinner.setMinimum(127);
		defaultVelocitySpinner.setMaximum(0);
		defaultVelocitySpinner.setValue(""+64);//center
		
		smoothLevel = new ParamCombo(s3,SWT.NULL,"smoothLevel",Messages.getString("wav2vsq.smoothLevel"),new String[]{"1","2","4","8"});
		smoothLevel.setValue("2");
		
		vocaloid1 =  new ParamBoolean(s3,SWT.NULL,"extension",Messages.getString("wav2vsq.vocaloid1"));
		vocaloid1.setValue("");
		vocaloid1.setToolTipText(Messages.getString("wav2vsq.vocaloid1_tooltip"));
		//swap extension
		vocaloid1.setParamItemActionListener(new ParamItemActionListener(){
			@Override
			public void paramItemModified(ParamItem item) {
				if(outputFileChooser.getAbsoluteFilePath().endsWith(".vsq") && ((ParamBoolean)item).getBoolean()){
					String path=FileNameUtils.getChangedExtensionName(outputFileChooser.getAbsoluteFilePath(), "mid");
					outputFileChooser.setFilePath(path);
				}else if(outputFileChooser.getAbsoluteFilePath().endsWith(".mid") && !((ParamBoolean)item).getBoolean()){
					String path=FileNameUtils.getChangedExtensionName(outputFileChooser.getAbsoluteFilePath(), "vsq");
					outputFileChooser.setFilePath(path);
				}
			}});
		
		inputWavFileChooser = new FileDirChoicer(parent,SWT.BORDER,FileDirChoicer.FILE,Messages.getString("wav2midi.wave"));
		inputWavFileChooser.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		inputWavFileChooser.addFileListChangeListener(selectedListener);
		inputWavFileChooser.setFilterExtensions(new String[]{"*.wav"});
		inputWavFileChooser.addFileListChangeListener(new ExportFileSet());
		
		inputSrtFileChooser = new FileDirChoicer(parent,SWT.BORDER,FileDirChoicer.FILE,Messages.getString("wav2midi.srt"),true);
		inputSrtFileChooser.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		inputSrtFileChooser.addFileListChangeListener(selectedListener);
		inputSrtFileChooser.setFilterExtensions(new String[]{"*.srt"});
		
		
		
		outputFileChooser = new FileDirChoicer(parent,SWT.BORDER,FileDirChoicer.SAVE,Messages.getString("wav2midi.vsq"),true);
		outputFileChooser.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		outputFileChooser.setFilterExtensions(new String[]{"*.vsq","*.mid"});
		outputFileChooser.addFileListChangeListener(selectedListener);
		
		
		
		wavToMidiExecuter.addControl(inputWavFileChooser);
		wavToMidiExecuter.addControl(inputSrtFileChooser);
		wavToMidiExecuter.addControl(outputFileChooser);
		
		Composite exec_label=WidgetBuilder.createGridLayoutComposite(parent,SWT.NULL,2, false);
		ExecutingControlButton exec=new ExecutingControlButton(exec_label,SWT.NULL,wavToMidiExecuter,
				Messages.getString("wav2midi.convert_vsq"),Messages.getString("cancel"));
		
		statusLabel = new Label(exec_label,SWT.NULL);
		statusLabel.setForeground(new Color(null,new RGB(255,0,0)));
		
		updateStatus();
		
		new DropMonitor(parent);
	}
	
	public class SettingMonitor implements IPropertyChangeListener {

		public void propertyChange(PropertyChangeEvent event) {
			log.info(event.getProperty());
			if (event.getProperty().equals(OtherToolsSettingPage.PATH_ASCII_TEMPORARY)) {
				updateStatus();
			} 
		}
	}
	
	public void setFocus() {
		
	}
	public void updateStatus() {
		//update label.
		if(wavToMidiExecuter.canExecute()){
			statusLabel.setText("");
		}else{
			if(tmpDirChooser.getAbsoluteFilePath().equals("") || !FileNameUtils.isAsciiFileName(tmpDirChooser.getAbsoluteFilePath())){
				statusLabel.setText(Messages.getString("wav2midi.choose_tmpdir"));
			}else if(inputWavFileChooser.getAbsoluteFilePath().equals("")){
				statusLabel.setText(Messages.getString("wav2vsq.choose_input"));
			}else if(outputFileChooser.getAbsoluteFilePath().equals("")){
				statusLabel.setText(Messages.getString("wav2vsq.choose_output"));
			}
		}
		
		// enable buttons and status.
		wavToMidiExecuter.updateControlSwitch();
	}
	private Composite createSplitComposite(Composite parent,int split,boolean same,Object data){
		Composite composite=new Composite(parent,SWT.NULL);
		composite.setLayout(new GridLayout(split,same));
		if(data!=null){
			composite.setLayoutData(data);
		}
		return composite;
	}
	private ParamTextArea createGridTextAreaGroup(Composite parent,String key,String label,Object data){
		/*Group group=new Group(parent,SWT.NULL);
		group.setText(label);
		group.setLayout(new FillLayout());
		group.setLayoutData(data);
		Text text=new Text(group,SWT.MULTI|SWT.V_SCROLL|SWT.H_SCROLL|SWT.BORDER);
		*/
		
		ParamTextArea text=new ParamTextArea(parent,SWT.NULL,key,label,ParamText.LAYOUT_FILL_BOTH);
		text.setLayoutData(data);
		return text;
	}
	
	private ParamText createLabeldText(Composite parent,String key,String label,Object data){
		ParamText text=new ParamText(parent,SWT.NULL,key,label,ParamText.LAYOUT_FILL_HORIZONTAL);
		if(data!=null){
			text.setLayoutData(data);
		}
		return text;
	}
	
	public class WavToVocaloidMIDIExecute extends ExecutingControler{
		
		private int min_pitch_value;
		private int max_pitch_value;
		private int min_volume_value;
		private int note_shift_value;
		private String inputWaveFileChooser_value;
		private String inputSrtFileChooser_value;
		
		private String outputFileChooser_value;
		
		private String tmpDirChooser_value;
		private boolean forceInsert;
		private boolean ignoreOffset;
		private double strechPlayTime;
		private boolean setVelocity;
		private boolean setPitch;
		private boolean velocityDetail;
		private boolean pitchDetail;
		private int defaultNote;
		private int defaultVelocity;
		private String scale_key;
		private String chorus_key;
		
		private int preMeasure_value;
		private int bentSens_value;
		private int gender;
		private int smoothLevel_value;
		public void afterExecute() {
			
		}

		@Override
		public void beforeExecute() {
			try{
			min_pitch_value=Integer.parseInt(min_picth.getValue());
			}catch(Exception e){
				
			}
			if(min_pitch_value==0){
				min_pitch_value=60;
			}
			try{
			max_pitch_value=Integer.parseInt(max_pitch.getValue());
			}catch(Exception e){
				
			}
			if(max_pitch_value==0){
				max_pitch_value=600;
			}
			
			forceInsert=forceInsertSubtile.getBoolean();
			ignoreOffset=ignoreOffsetBoolean.getBoolean();
			strechPlayTime=Double.parseDouble(strechTimeSale.getValue())/10;
			
			min_volume_value=(int) Double.parseDouble(minVolumeScale.getValue());
			note_shift_value=(int) Double.parseDouble(noteShiftScale.getValue());
			
			setVelocity=setVelocityBoolean.getBoolean();
			velocityDetail=setVelocityDetailBoolean.getBoolean();
			
			setPitch=setPitchBoolean.getBoolean();
			pitchDetail=setPitchDetailBoolean.getBoolean();
			defaultNote=(int) Double.parseDouble(defaultPitchSpinner.getValue());
			defaultVelocity=(int) Double.parseDouble(defaultVelocitySpinner.getValue());
			
	
			
			inputWaveFileChooser_value=inputWavFileChooser.getAbsoluteFilePath();
			inputSrtFileChooser_value=inputSrtFileChooser.getAbsoluteFilePath();
			outputFileChooser_value=outputFileChooser.getAbsoluteFilePath();
			
			tmpDirChooser_value=tmpDirChooser.getAbsoluteFilePath();
			
			preMeasure_value=Integer.parseInt(preMeasure.getValue());
			bentSens_value=Integer.parseInt(bentSens.getValue());
			
			gender=(int) Double.parseDouble(genderScale.getValue());
			
			smoothLevel_value=(int) Double.parseDouble(smoothLevel.getValue());
		}

		@Override
		public boolean canExecute() {
			if(!FileNameUtils.isAsciiFileName(tmpDirChooser.getAbsoluteFilePath())){
				return false;
			}
			return !inputSrtFileChooser.getAbsoluteFilePath().equals("") && !inputWavFileChooser.getAbsoluteFilePath().equals("") &&!outputFileChooser.getAbsoluteFilePath().equals("") ;
			
		}

		@Override
		public void cancelExecuting() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void inExecute() {
			String pitch2ExePath=Akj_betasPlugin.getDefault().getPreferenceStore().getString(AudioToolsSettingPage.PATH_PITCH2);
			if(pitch2ExePath.equals("")){
				StatusBarUtils.showStatusBar("pitch2.exe is not setted in OtherTools setting");
				return;
			}
			File output=new File(outputFileChooser_value);
			
			File waveFile=new File(inputWaveFileChooser_value);
			AudioFileFormat format=null;
			try {
				format=AudioSystem.getAudioFileFormat(waveFile);
			} catch (UnsupportedAudioFileException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			if(format==null){
				//mea
				log.warn("wrong wave");
				return;
			}
			
			
			File input;
			File tmp=null;
			if(FileNameUtils.isAsciiFileName(inputWaveFileChooser_value) &&(int)format.getFormat().getSampleRate()==48000){
			input=new File(inputWaveFileChooser_value);
			}else{
			input=new File(tmpDirChooser_value,System.currentTimeMillis()+".wav");
			tmp=input;
			tmp.deleteOnExit();
			if((int)format.getFormat().getSampleRate()==48000){
				try {
					FileUtils.copyFile(waveFile, input);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else{
				String ffmpeg=FFMpegUI.getFFmpegOrPureFFMpeg();
				if(ffmpeg==null){
					log.warn("no ffmpeg and copy");
					try {
						FileUtils.copyFile(waveFile, input);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}else{
					SimpleCommandExecuter executer=new SimpleCommandExecuter(FFMpegCommandUtil.makeWaveSampleRateChangeCommand(ffmpeg, waveFile.getAbsolutePath(), input.getAbsolutePath(), 48000));
					executer.setPrinter(Akj_betasPlugin.getDefault().getProcessPrinter());//for debug
					executer.execute();
					StatusBarUtils.showStatusBar("");
					}
				}
			}
			
			PitchExecuter executer=new PitchExecuter();
			executer.setPitch2ExePath(pitch2ExePath);
			
			ESPS[] esps;
			try {
				int detailLevel=smoothLevel_value;//how smooth pitch,values 1,2,4,8
				String commands[]=executer.getCommands(input.getAbsolutePath(), 0, 0,min_pitch_value,max_pitch_value,0.03125/(2*detailLevel));// 1/64 = 0.03125/2
				log.info(FFMpegUtils.toPrintCommand(commands));
				Akj_betasPlugin.getDefault().getProcessPrinter().printOutput("###\n"+FFMpegUtils.toPrintCommand(commands)+"\n");
				esps = executer.getESPS(input.getAbsolutePath(), 0, 0,min_pitch_value,max_pitch_value,0.03125/(2*detailLevel));
				
				
				
				
				
				//esps=SnackExecuter.toAverage(esps,2);
				PitchToVocaloidMIDI p2midi=new PitchToVocaloidMIDI();
				p2midi.setDetailLevel(detailLevel);
				
				p2midi.setShiftNote(note_shift_value);
				p2midi.setVolumeMin(min_volume_value);
				
				p2midi.setIgnoreOffset(ignoreOffset);
				p2midi.setForceInsert(forceInsert);
				
				p2midi.setParseNote(setPitch);
				p2midi.setParseVelocity(setVelocity);
				
				p2midi.setDefaultNote(defaultNote);
				p2midi.setDefaultVelocity(defaultVelocity);
				
				p2midi.setPreMeasure(preMeasure_value);
				p2midi.setMaxBendSens(bentSens_value);
				p2midi.setGender(gender);
				
				p2midi.setDetailDynamics(velocityDetail);
				p2midi.setDetailPitch(pitchDetail);
				
				if(StringUtils.isNotEmpty(chorus_key)){
					p2midi.setChorusLine(chorus_key);
				}
				if(StringUtils.isNotEmpty(scale_key)){
					//C only
					int codes[]=Scale.getCodeScale(scale_key);//start with 1
					p2midi.setScaleFilter(codes);
				}
				
				
				
				p2midi.setTempo((int) (120/strechPlayTime));
				
				System.out.println(ignoreOffset+","+forceInsert+","+strechPlayTime);
				
				if(!inputSrtFileChooser_value.equals("")){
				StandardSubObject[] subtitles=loadSubtitles(new File(inputSrtFileChooser_value));
				p2midi.makeVocaloidMIDI(esps, subtitles,output);
				}else{
				throw new IOException("never");
				
				}
				
				StatusBarUtils.showStatusBar(Messages.getString("wav2vsq.created")+output.getName());
				if(tmp!=null){
					tmp.delete();
				}
			} catch (IOException e) {
				StatusBarUtils.showStatusBar("faild:"+output.getName());
				Akj_betasPlugin.getDefault().getProcessPrinter().printOutput(e.getMessage()+"\n");
				e.printStackTrace();
			}
			
			Akj_betasPlugin.getDefault().getProcessPrinter().printOutput("###\n");
			
			
		}
		
		
	}
	public StandardSubObject[] loadSubtitles(File file){
		if(file==null || !file.exists()){
			return new StandardSubObject[0];
		}
		SRTParser parser=new SRTParser();
		SRTList list;
		try {
			list = parser.parse(new FileReader(file));
			List<StandardSubObject> subList=list.convertStandardSubtitleDataList();
			return subList.toArray(new StandardSubObject[subList.size()]);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 return new StandardSubObject[0];
	}

	public class FileSelected implements FileStatusChangeListener{

		public void addList(FileStatusChangeEvent event) {
			
			updateStatus();
		}

		public void removeList(FileStatusChangeEvent event) {
			updateStatus();
		}
		
	}
	

	public class DropMonitor extends DropTargetAdapter {
		public DropMonitor(Composite controler){
			Transfer[] types = new Transfer[] { FileTransfer.getInstance() };

			int operations = DND.DROP_MOVE | DND.DROP_COPY;

			DropTarget target2 = new DropTarget(controler, operations);
			target2.setTransfer(types);

			target2.addDropListener(this);
		}
		public void dragEnter(DropTargetEvent event) {
			// log.infodrag enter:"+event.data);
		}

		public void dragOver(DropTargetEvent event) {
			// log.infodrag over:"+event.data);
		}

		public void drop(DropTargetEvent event) {
			//log.info("cancovert:"+isCanConvert());
					
			String files[] = (String[]) event.data;

			
			for (int i = 0; i < files.length; i++) {
				
				if(FileNameUtils.isWaveFile(files[i]) && new File(files[i]).isFile()){
				inputWavFileChooser.setFilePath(files[i]);
				setInputWave(files[i]);
				break;	//now first 1 file only
				}else if(FileNameUtils.getExtension(files[i]).toLowerCase().equals("vsq")){
					outputFileChooser.setFilePath(files[i]);
					wavToMidiExecuter.updateControlSwitch();
					break;
				}
			}
			
		}
	}

	public void setInputWave(String path) {
	
		String exportPath;
		if(vocaloid1.getBoolean()){
			exportPath=FileNameUtils.getChangedExtensionName(new File(path), "mid",true);
		}else{
			exportPath=FileNameUtils.getChangedExtensionName(new File(path), "vsq",true);
		}
		
		if(!new File(exportPath).exists()){//dont overwrite automatic
			outputFileChooser.setFilePath(exportPath);
		}
		
		String srtPath=FileNameUtils.getChangedExtensionName(new File(path), "srt",true);
		if(new File(srtPath).exists()){//dont overwrite automatic
			inputSrtFileChooser.setFilePath(srtPath);
		}
		updateStatus();
	}
		
}